package cn.tedu.shoot;

import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WriteScore {
	public static void write(){
		try(RandomAccessFile raf = new RandomAccessFile("score.txt","rw")) {
			raf.seek(raf.length());
			String str = World.heroNum+1+"号战机";
			byte[] data = str.getBytes("UTF-8");
			data = Arrays.copyOf(data, 20);
			raf.write(data);
			
			str = World.score+"";
			data = str.getBytes("UTF-8");
			data = Arrays.copyOf(data, 20);
			raf.write(data);
			
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 ");//a E
			str = sdf.format(date);
			byte[] day = str.getBytes("UTF-8");
			day = Arrays.copyOf(day, 60);
			raf.write(day);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static List<String> read(){
		List<String> list = new ArrayList<>();
		List<Integer> key = socreHigh();//得到排行榜分数最高的列次
		int a = 0;
		try (RandomAccessFile raf = new RandomAccessFile("score.txt","r")){
			for(Integer i : key){
				if(a++<10){//让排行榜只有10名
					raf.seek(i*100);
					byte[] data = new byte[20];
					raf.read(data);
					String str = new String(data,"UTF-8").trim();
					list.add(str);
					
					raf.read(data);
					str = new String(data,"UTF-8").trim();
					list.add(str);
					
					data = new byte[60];
					raf.read(data);
					str = new String(data,"UTF-8").trim();
					list.add(str);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	private static List<Integer> socreHigh(){
		List<Integer> list = new ArrayList<>();
		Map<Integer,Integer> map = new HashMap<>(); 
		List<Integer> key = new ArrayList<>();
		try (RandomAccessFile raf = new RandomAccessFile("score.txt","r")){
			for(int i=0;i<raf.length()/100;i++){
				raf.seek(i*100+20);
				byte[] data = new byte[20];
				raf.read(data);
				String str = new String(data,"UTF-8").trim();
				int m = Integer.parseInt(str);
				map.put(i, m);
				list.add(m);
			}
			Collections.sort(list,new Comparator<Integer>() {//匿名内部类从大到小排序
				@Override
				public int compare(Integer o1, Integer o2) {
					return o2-o1;
					
				}
			});
				for(int i=0;i<list.size();i++){
					if(i>0&&list.get(i)==list.get(i-1)){
						continue;//如果有重复的元素则跳过本次循环
					}
					for(int j=0;j<raf.length()/100;j++){
						if(list.get(i).equals(map.get(j))){
							key.add(j);
						}
					}
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return key;
	}
//	public static void main(String[] args) {
//		List<String> list = read();
//		int i = 1;
//		for(String str:list){
//			System.out.print(str+"   ");
//			if(i++%3==0){
//				System.out.println();
//			}
//		}
//	}
}
